package cn.zn.modules.zzsys.cur.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.zn.framework.common.exception.RRException;
import cn.zn.modules.zzsys.cur.dao.SysWxmpDao;
import cn.zn.modules.zzsys.cur.entity.SysPushSetup;
import cn.zn.modules.zzsys.cur.entity.SysWxmpEntity;
import cn.zn.modules.zzsys.cur.service.SysPushSetupService;
import cn.zn.modules.zzsys.cur.service.SysWxmpService;
import cn.zn.modules.zzsys.push.pzevent.PushMsgPzProcessEvent;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpTemplateMsgServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SysWxmpServiceImpl extends ServiceImpl<SysWxmpDao, SysWxmpEntity> implements SysWxmpService {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SysPushSetupService sysPushSetupService;

    @Override
    public void pushTmpMsgPzProcessEnent(String mqMsgJson) {
        PushMsgPzProcessEvent pushMsgPzProcessEvent = JSON.parseObject(mqMsgJson, PushMsgPzProcessEvent.class);
        Assert.notNull(pushMsgPzProcessEvent.getEventType());
        Assert.notNull(pushMsgPzProcessEvent.getApplyCode());
        Assert.notNull(pushMsgPzProcessEvent.getWorkNo());
        // 查询推送人员
        SysWxmpEntity sysWxmpEntity = this.getById(pushMsgPzProcessEvent.getWorkNo());
        if (sysWxmpEntity == null) {
            // TODO 记录未发送成功的消息，以备重发
            log.error("消息推送失败，人员的微信公众号关系不存在: {}", mqMsgJson);
            return;
        }
        // 整理推送消息
        SysPushSetup sysPushSetup = sysPushSetupService.getByMsgCode(pushMsgPzProcessEvent.getEventType());
        if (sysWxmpEntity == null) {
            // TODO 记录未发送成功的消息，以备重发
            log.error("消息推送失败，推送配置不存在: {}", mqMsgJson);
            return;
        }
        String formatSQL = StrUtil.format(sysPushSetup.getQuerySql().replace("?", "'{}'"), pushMsgPzProcessEvent.getApplyCode());
        log.debug("formatSQL: {}", formatSQL);
        List<Map<String, Object>> maps = this.baseMapper.queryForPush(formatSQL);
        log.debug("maps: {}", maps);
        if (!maps.isEmpty()) {
            List<WxMpTemplateData> datas = maps.get(0).entrySet().stream().map(o -> {
                String value = "", color = null;
                if (o.getValue() != null) {
                    String[] valueAndColor = o.getValue().toString().split("&");
                    value = valueAndColor[0];
                    if(valueAndColor.length == 2){
                        color = valueAndColor[1];
                    }
                }
                return new WxMpTemplateData(o.getKey(), value, color);
            }).collect(Collectors.toList());
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setToUser(sysWxmpEntity.getOpenId());
            message.setTemplateId(sysPushSetup.getTmpId());
            message.setData(datas);
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(message);
            } catch (WxErrorException e) {
                log.error("", e);
                throw new RRException(e.getMessage());
            }
        }

    }
}